<template>
	<view class="content">
		<u-navbar
			back-text=""
			 back-icon-size="36" 
			 :border-bottom="false"
			 :custom-back="customBack">
			 
		 </u-navbar>
		<!-- <view class="back">
			<image @click="back" src="@/static/img/common/topBack.png" alt="" />
		</view> -->
		<view class="yjTitle _df _jb _ac" style="padding: 0 20rpx;">
			<span>添加设备</span>
			<image @click="refresh" src="@/static/img/index/shuaxin.png" mode="" style="width: 41rpx;height: 36rpx;"></image>
		</view>
		<view class="subTitle" v-if="myBleDevs.length>0">
			我的设备
		</view>
		<view class="my-box box" v-if="myBleDevs.length>0">
			<view class="item2 _df _ac _jb" v-for="(item, index) in myBleDevs" :key="index">
				<view class="mr30">
					<image class="img1" src="@/static/img/index/watch.png" mode=""></image>
				</view>
				<view class="" style="margin-right: auto;">
					<view class="title">
						{{item.name}}
					</view>
					<view class="info">
						当前设备
					</view>
				</view>
				<view >
					<image v-if="isJoin" class="img2" src="@/static/img/index/gou.png" mode=""></image>
					<u-loading v-else mode="flower" size="34"></u-loading>
				</view>
			</view>
		</view>
		<view class="box1 _df _ac _jb box" v-if="isSearch">
			<u-loading mode="circle" size="36"></u-loading>
			<span style="margin: 0 auto 0 10rpx;">正在搜索可发现的设备...</span>
			
		</view>
		
		<!-- <view class="subTitle">
			我的设备
		</view>
		<view class="my-box box">
			<view class="item _df _ac" v-for="(item,index) in myBleDevs" :key="index">
				<view class="">
					{{item.name}}
				</view>
			</view>
		</view> -->
		<view class="subTitle _df _ac">
			<view class="mr20">其他设备</view>
			<u-loading mode="circle" size="28" v-if="!isSearch"></u-loading>
		</view>
		<view class="other-box box">
			<view @click="createBLEConnection(item,'0x01')" class="_df _jb item" v-for="(item,index) in bleDevs" hover-class="hover" :key="index">
				<view class="">
					{{item.name}}
				</view>
				
			</view>
		</view>
		<!-- <view class="subTitle _df _ac">
			<view class="mr20">返回数据</view>
		</view>
		<view class="other-box box">
			<view class="_df _jb item" v-for="(item,index) in valueList" hover-class="hover" :key="index">
				<view class="">
					{{item.name}}：{{item.value}}
				</view>
				<view class="">
					{{item.data}}
				</view>
			</view>
		</view> -->
		<!-- <view class="other-box box">
			<view @click="dowrite('da01010001','0x01')" class="_df _jb item" hover-class="hover">
				<view class="">
					绑定指令
				</view>
				
			</view>
			<view @click="dowrite('da0b0000','0x0b')" class="_df _jb item" hover-class="hover">
				<view class="">
					蓝牙系统配对指令
				</view>
				
			</view>
			<view @click="dowrite('da020700000000000a4a01','0x02')" class="_df _jb item" hover-class="hover">
				<view class="">
					设备状态指令
				</view>
				
			</view>
			<view @click="dowrite('da060000','0x06')" class="_df _jb item" hover-class="hover">
				<view class="">
					获取电量
				</view>
				
			</view>
			<view @click="dowrite('da0d0000','0x0d')" class="_df _jb item" hover-class="hover">
				<view class="">
					获取当前设备展示数据
				</view>
				
			</view>
			<view @click="dowrite('da0e0600010101010101','0x0e')" class="_df _jb item" hover-class="hover">
				<view class="">
					健康数据检测开关指令
				</view>
				
			</view>
			
		</view> -->
		<!-- <view class="sys" @click="snacode">
			<view class="btn">扫一扫</view>
		</view> -->
	</view>
</template>

<script>
	// import {Buffer  } from 'buffer';
	import {checkOpenGPSServiceByAndroid } from '@/utils/openSettings.js';
	export default {
		data() {
			return {
				bleDevs:[],//其他设备
				myBleDevs:[],//我的设备
				name:'',
				deviceId:'',//设备 id
				serviceId:'6E400001-B5A3-F393-E0A9-E50E24DCCA9D',//蓝牙特征值对应服务的 uuid
				notifyUuid:'',//开启蓝牙消息监听 uuid
				writeId:'',//蓝牙写入指令 uuid
				resHex:'',
				characteristics:[],
				characteristicId:'',
				crcValue:"",
				originalData:'',//指令
				type:'',//指令类型
				platform:'',//手机系统android/ios/未知
				isSearch:true,
				isJoin:false,//是否连接
				dataList:[],//实际值
				valueList:[],//数据返回数组
				isWrite:false,
				isopenBlue:false,
				swipeShow:false,
				options: [
					{
						text: '断开',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				]
			};
		},
		
		onShow() {
			this.getLocation()
			this.initBle()
			this.getWatch()
		},
		onLoad() {
			
			// this.crcValue=this.getCrc_16_ibm(this.originalData);
			const systemInfo = uni.getSystemInfoSync();
			this.platform = systemInfo.platform;
			if (this.platform === 'android') {
			    console.log('当前系统是安卓');
			    
				
			} else if (this.platform === 'ios') {
			    console.log('当前系统是iOS');
			} else {
			    console.log('平台未知：', this.platform);
			}
		},
		methods:{
			getLocation(){
				let that = this
				uni.getLocation({
					type: 'wgs84',
					geocode:true,
					success: function (res) {
						// console.log(res);
						// console.log('当前位置的经度：' + res.longitude);
						// console.log('当前位置的纬度：' + res.latitude);
						// that.getAddress()
					},
					fail: function (err) {
						uni.showModal({
							title: '提示',
							content: '为了您更好的体验App蓝牙功能，需要获取位置信息，请点击设置开启定位权限。',
							confirmText: '去开启',
							// showCancel:false,
							success: function(res) {
							  if (res.confirm) {
								// 用户点击确认，跳转到设置页面
								checkOpenGPSServiceByAndroid()
							  } else {
							  }
							}
						  });
					},
				});
			},
			customBack(){
				uni.switchTab({
					url:'/pages/tabbar/health/index'
				})
			},
			swipeclick(index, index1) {
				this.writeFn('da15010000','0x14')
				
			},
			// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
			
			refresh(){
				this.initBle()
				this.getWatch()
			},
			getWatch(){
				let that = this;
				let myblue = []
				uni.$_get({
					url: "get-watch",
					that: that,
					success(res) {
						let _data = res.data;
						if(res.code == 0){
							console.log(_data,'当前手表')
							if(_data!=null && _data.deviceId){
								that.deviceId = _data.deviceId
								that.serviceId = _data.serviceId
								that.notifyUuid = _data.notifyUuid
								that.writeId = _data.writeId
								// that.isJoin = true
								let obj = {
									name:_data.name,
									deviceId:_data.deviceId,
								}
								if(that.deviceId!=''){
									myblue.push(obj)
									that.myBleDevs = myblue
									that.isSearch = false
								}
								that.createBLEConnection(obj,'0x0b')
								
							}
							
						}
						
					},
					fail(err) {
						
					},
				});
			},
			back(){
				uni.navigateBack(-1)
			},
			getCrc_16_ibm(cData_str) {
			      let arr = [];
			      let len = cData_str.length / 2
			      for (let i = 0; i < len; i++) {
			        let a = '0x' + cData_str.slice(i * 2, i * 2 + 2);
			        arr.push(a);
			      }
			      let crc = this.CRC16_IBM(arr);
			      let crcLen = crc.length;
			      crc = crcLen >= 4 ? crc.slice(2, 4) + crc.slice(0, 2) : crcLen == 3 ? crc.slice(1, 3) + '0' + crc.slice(0, 1) : crcLen == 2 ? crc + '00' : '0' + crc + '00';
			      return crc;
			},
			CRC16_IBM(cData) {
			      let cLen = cData.length;
			      let CRC16Table = [
			        0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
			        0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
			        0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
			        0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
			        0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
			        0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
			        0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
			        0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
			        0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
			        0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
			        0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
			        0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
			        0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
			        0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
			        0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
			        0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
			        0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
			        0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
			        0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
			        0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
			        0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
			        0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
			        0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
			        0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
			        0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
			        0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
			        0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
			        0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
			        0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
			        0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
			        0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
			        0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
			      ];
			
			      var result = 0;
			      var tableNo = 0;
			
			      for (let i = 0; i < cLen; i++) {
			        tableNo = ((result & 0xff) ^ (cData[i] & 0xff));
			        result = ((result >> 8) & 0xff) ^ CRC16Table[tableNo];
			      }
			      return result.toString(16).toUpperCase();
			    },
			//初始化蓝牙
			initBle() {
				//关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源。
				uni.closeBluetoothAdapter({
					success(res) {
						// console.log(res)
						
					}
				});
				// console.log('初始化蓝牙>>>');
				// uni.showLoading({
				// 	title: '设备连接中,请稍后',
				// });
				uni.openBluetoothAdapter({
					success: (res) => { //已打开
						uni.getBluetoothAdapterState({ //蓝牙的匹配状态
							success: (res1) => {
								// console.log(res1, '“本机设备的蓝牙已打开”')
								this.isopenBlue = true
								this.startBluetoothDeviceDiscovery();
								// this.getWatch()
							},
							fail(error) {
								this.isopenBlue = false
								// uni.showToast({
								// 	icon: 'none',
								// 	title: '请打开手机蓝牙'
								// });
							}
						});

					},
					fail: err => { //未打开
						this.isopenBlue = false
						uni.showToast({
							icon: 'none',
							title: '请打开手机蓝牙'
						});
						// uni.switchTab({
						// 	url: '../index/index'
						// })
					}
				})
			},

			//开始搜索蓝牙设备
			startBluetoothDeviceDiscovery() {
				// uni.showLoading({
				// 	title: '搜索设备中,请稍后',
				// });
				
				uni.startBluetoothDevicesDiscovery({
					// allowDuplicatesKey:true,
					success: (res) => {
						
						// console.log(res,'搜索结果一')
						// 发现外围设备
						this.onBluetoothDeviceFound()
					},
					fail: err => {
						console.log(err, '开始搜索蓝牙设备备错误信息')
					}
				})
			},
			// 发现外围设备
			onBluetoothDeviceFound() {
				// console.log("执行到这--发现外围设备")
				let bleDevs = [];
				let that = this
				uni.onBluetoothDeviceFound((res) => {
					// console.log(res, '发现外围设备');
					//遍历周围的设备
					res.devices.forEach(ele => {
						if(ele.name){
							bleDevs.push(ele);
							if(that.myBleDevs.length>0){
								let arr = bleDevs.filter((item) =>item.name != that.myBleDevs[0].name)
								that.bleDevs = Array.from(new Set(arr))
							}else{
								that.bleDevs = Array.from(new Set(bleDevs))
							}
						}
						
						
					})
					// this.bleDevs = bleDevs
					// console.log(that.ab2hex(res[0].advertisData),333)
					// 把搜索到的设备存储起来，方便我们在页面上展示
					// console.log("蓝牙列表", this.bleDevs);
					// uni.hideLoading();
				})
			},
			// item 是要连接的设备数据
			createBLEConnection(item,type) {
				console.log(item,999)
				let that = this;
				uni.showLoading({
					title: "连接中，请稍等",
					mask: false,
				});
				this.type = type
				that.deviceId = item.deviceId
				that.name = item.name
				uni.createBLEConnection({
					deviceId: item.deviceId,
					success(res) {
						// that.bleDevs.find(item2 => item2.deviceId == item.deviceId).isConnected = true
						// uni.stopBluetoothDevicesDiscovery(); // 停止搜索蓝牙
						that.getBLEDeviceServices(item);	// 获取蓝牙的服务
						// setTimeout(() => {
						// 	uni.hideLoading();
							
						// }, 1000);
						// that.myBleDevs.push(item)
						// console.log(that.bleDevs,666)
						that.bleDevs = that.bleDevs.filter((item2) => item2.deviceId !== item.deviceId)
						that.myBleDevs.splice(0,1,item)
						that.isSearch = false
						that.isJoin = false
						
					},
					fail(res) {
						console.log(res)
						uni.showToast({
							title: item.name + "连接失败",
							icon: "none",
						});
						uni.hideLoading()
					}
				});
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				let that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						success: (res) => {
							console.log("蓝牙服务", res);
							// that.serviceId = res.services[0].uuid
							//进入特征
							that.getBLEDeviceCharacteristics()
						}
					})
				}, 1500)
			},
			//获取蓝牙特征列表
			getBLEDeviceCharacteristics() {
				let that = this;
				// console.log("进入特征");
				uni.getBLEDeviceCharacteristics({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					success: (res) => {
						// console.log("蓝牙特征", res);
						for (var i = 0; i < res.characteristics.length; i++) { //2个值
							var model = res.characteristics[i]
							if (model.properties.write) {
								//model.uuid:用来写入的uuid值
								//this.sendMy()给设备写入
								// that.sendMy(model.uuid)
								that.writeId = model.uuid
							}
							if (model.properties.notify) {
								//model.uuid:用来notify的uuid值
								that.notifyUuid = model.uuid
							}
						}
						// that.startNotice()
						// that.characteristicId = res.characteristics[1].uuid
						// that.getPage(that.deviceId);
						// that.getReadBLECharacteristicValue();
						// that.writeBLECharacteristicValue();
						// setTimeout(() => {
						// 	//这里可以处理一些业务逻辑
						// }, 1000);
						// that.readBLECharacteristicValue()
						setTimeout(()=>{
							if(this.type == '0x01'){
								if(this.platform === 'android'){
									that.writeFn('da01010001','0x01')
								}else{
									that.writeFn('da01010002','0x01')
								}
								
							}else{
								that.writeFn('da0b0000','0x0b')
							}
						},500)
						
						
					},
					fail: (res) => {
						console.log(res,'失败');
						uni.hideLoading()
					}
				})
			},
			dowrite(data,type){
				this.originalData = data
				this.type = type
				this.writeFn(data,type)
			},
			writeFn(data,type){
				var that = this
				let crc = uni.$_getCrc_16_ibm(data)
				let val = data + crc
				console.log(val,'发送的指令')
				//指令类型
				this.type = type
				let buff = uni.$_hexStringToArrayBuffer(val)
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.writeId, //第二步写入的特征值
					// 这里的value是ArrayBuffer类型
					value: buff,
					success: function(res) {
						//此时设备已接收到你写入的数据
						console.log("连接写入成功",res)
						if(that.type == '0x0b'){
							that.isJoin = true
							uni.$_setStorage('isJoin',JSON.stringify(that.isJoin))
						}
						that.startNotice(type)
					},
					fail: function(err) {
						console.log(err)
						uni.hideLoading()
					},
					// complete: function() {
					// 	console.log("调用结束");
						
					// }
				})
				
				// let buff = this.generate_command(0xDA, 0x01,[0x01,0x02])
				
				// that.listenValueChange()
			},
			read() {
				let that = this
			    uni.readBLECharacteristicValue({
			        deviceId: that.deviceId,
			        serviceId: that.serviceId,
			        characteristicId: that.writeId,
			        success(res) {
			            console.log('读取指令发送成功')
			            console.log(res)
			        },
			        fail(err) {
			            console.log('读取指令发送失败')
			            console.error(err)
						uni.hideLoading()
			        }
			    })
			},
			watchLinkRecord(){
				let that = this;
				let p = {
					name:this.name,
					deviceId:this.deviceId,//设备 id
					serviceId:this.serviceId,//蓝牙特征值对应服务的 uuid
					notifyUuid:this.notifyUuid,//开启蓝牙消息监听 uuid
					writeId:this.writeId,//蓝牙写入指令 uuid
				}
				if(this.type == '0x01'){
					uni.$_post({
						url: "watchLinkRecord",
						that: that,
						params: p,
						success(res) {
							let _data = res.data;
							if(res.code == 0){
								uni.showToast({
									title:'连接成功',
									icon:'success'
								})
								
							}
							
						},
						fail(err) {
							
						},
					});
				}
				
			},
			startNotice(type) {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
					success(res) {
						//接收蓝牙返回消息
						// console.log(res,'蓝牙返回消息')
						// that.listenValueChange()
						uni.onBLECharacteristicValueChange(result => {
							// console.log("监听低功耗蓝牙设备的特征值变化", result);
							if (result.value) {
								let resHex = that.ab2hex(result.value)
								console.log('设备返回数据', resHex)
								let dataObj = that.parse_blue_response(resHex,2)
								
								console.log('拆分数据', dataObj)
								// uni.showLoading({
								// 	title: "正在获取设备数据",
								// 	mask: true,
								// });
								// if(dataObj.Head == '00') {
								// 	// uni.showToast({
								// 	// 	title:'获取失败！请重试',
								// 	// 	icon:'none'
								// 	// })
								// 	// uni.hideLoading()
								// 	setInterval(() =>{
								// 		that.writeFn(that.originalData,that.type)
								// 	},500)
								// 	// return
								// }else if(!dataObj.Head){
								// 	setInterval(() =>{
								// 		that.writeFn(that.originalData,that.type)
								// 	},500)
								// }
								// else{
									
									
								// }
								// clearInterval()
								if(dataObj.Cmd){
									if(that.type=='0x01'){
										that.watchLinkRecord()
										uni.hideLoading()
										that.isJoin = true
										uni.$_setStorage('isJoin',JSON.stringify(that.isJoin))
									}
									if(that.type == '0x0b'){
										uni.hideLoading()
										that.isJoin = true
										uni.$_setStorage('isJoin',JSON.stringify(that.isJoin))
									}
									
								}
								// switch (type){
								// 	case '0x01':
									
									
									
								// 	that.valueList = [
								// 		{
								// 			name:'错误码',
								// 			len:1,
								// 			value:'',
								// 			data:'',
								// 			dataLen:0
											
								// 		},
								// 		{
								// 			name:'系统类型',
								// 			len:1,
								// 			value:'',
								// 			data:'',
								// 			dataLen:0
								// 		}
										
								// 	]
								// 	that.dataToArr(dataObj.Data)
								// 	break
								// 	case '0x0d':
										
								// 		that.valueList = [
								// 				{
								// 					name:'错误码',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
													
								// 				},
								// 				{
								// 					name:'总的计步值',
								// 					len:4,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'总的卡路里(卡)',
								// 					len:4,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'总的距离(m)',
								// 					len:4,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'睡眠总时间(分钟)',
								// 					len:2,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'深睡时间',
								// 					len:2,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'浅睡时间',
								// 					len:2,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'当前心率',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'低压',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'高压',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'当前血氧',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'当前压力',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'当前梅脱',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'当前MAI',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'当前体温（显示需除以100）',
								// 					len:2,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'当前血糖（显示需除以10）',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 				{
								// 					name:'是否佩戴',
								// 					len:1,
								// 					value:'',
								// 					data:'',
								// 					dataLen:0
								// 				},
								// 		]
								// 		that.dataToArr(dataObj.Data)
								// 	break 
								// 	case 3:
									
								// 	break
								// }
								
								
								
								
							}
						})
						
					},
					fail(err) {
						console.log(err)
						uni.hideLoading()
					}
				})
			},
			listenValueChange() {
				let that = this
				// console.log('获取返回结果')
				uni.onBLECharacteristicValueChange((sjRes)=>{
					// console.log(sjRes,'返回总数据')
					// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据，
					//所以需要通过一个方法转换成字符串
					that.resHex = that.ab2hex(sjRes.value)//10.0
					let value = that.parse_blue_response(that.resHex)
					let newVal = that.array16_to_number(value)
					let newVal2 = that.hex2int(that.resHex)
					let result = that.hexCharCodeToStr(that.resHex)
					
					console.log(that.resHex,'16进制数据')	
					console.log(value,'拆分数据')	
					console.log(newVal,'新数据')
					console.log(newVal2,'新数据2')
					// console.log(String(result),555)
					// that.read()
				})
			},
			//返回的数据拆分
			dataToArr(dataList){
				this.valueList.forEach((item,index) =>{
					if(index == 0){
						item.dataLen = item.len
						item.value  = dataList.slice(0,item.dataLen)
					}else{
						item.dataLen = this.valueList[index-1].dataLen +this.valueList[index].len
						if(item.len>=2){
							let itemArr = dataList.slice(this.valueList[index-1].dataLen,item.dataLen).reverse()
							let str = itemArr.join('')
							item.value = str
							item.data = this.hex2int(str)
						}else{
							let itemArr = dataList.slice(this.valueList[index-1].dataLen,item.dataLen)
							let str = itemArr.join('')
							item.value = str
							item.data = this.hex2int(str)
							
						}
					}
				})
				// uni.showToast({
				// 	title:'获取成功！',
				// 	icon:'success'
				// })
				uni.hideLoading()
			},
			// responseData 的值为第 7 点中的 resHex
			parse_blue_response(str,chunkSize) {
				const regex = new RegExp('.{1,' + chunkSize + '}', 'g');
				let arr = Array.from(str.match(regex) || [])
				let dataList = []
				dataList = arr.slice(4,-2)
				let obj = {
					Head:arr[0],
					Cmd:arr[1],
					Data_len:arr[2]+ arr[3],
					Data:dataList,
					Check_Crc:arr.slice(-2),
				}
				  return obj;
				// const dataList = responseData.match(/.{1,2}/g)
				// const resCode= dataList.splice(0, 1)
				// const resType= dataList.splice(1, 1)
				// const resResult= dataList.splice(3, 1)
				// const [resCode, resType, resResult] = dataList.splice(0, 3)
				// resCode：响应包起始码；
				// resType：指令码
				// resResult：数据长度
				// dataList：其他响应数据 + 空数据，Array 格式数据
				// return dataList
			},
			generate_command(startCode, dataType, sentData) {
				let buffer = new ArrayBuffer(20)
				let dataView = new DataView(buffer)
				dataView.setUint8(0, startCode)
				dataView.setUint8(1, dataType)
				let _beforeIndex = 2
				
				if(sentData) {
					for (var k = 0; k < sentData.length; k++) {
						dataView.setUint8(k + _beforeIndex, sentData[k])
					}
					_beforeIndex += sentData.length
				}
				return buffer
			},
			// 16进制转buffer
			hexStringToArrayBuffer(str) {
				if (!str) {
					return new ArrayBuffer(0);
				}
				var buffer = new ArrayBuffer(str.length);
				let dataView = new DataView(buffer)
				let ind = 0;
				for (var i = 0, len = str.length; i < len; i += 2) {
					let code = parseInt(str.substr(i, 2), 16)
					dataView.setUint8(ind, code)
					ind++
				}
				return buffer;
			},
			
			// 将16进制的内容转成我们看得懂的字符串内容
			hexCharCodeToStr(hexCharCodeStr) {
			    var trimedStr = hexCharCodeStr.trim();
			    var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
			    var len = rawStr.length;
			    if (len % 2 !== 0) {
			            alert("存在非法字符!");
			            return "";
			    }
			    var curCharCode;
			    var resultStr = [];
			    for (var i = 0; i < len; i = i + 2) {
			            curCharCode = parseInt(rawStr.substr(i, 2), 16);
			            resultStr.push(String.fromCharCode(curCharCode));
			    }
			    return resultStr.join("");
			},
			// 16进制转10进制整数
			hex2int(hex) {
				var len = hex.length,
					a = new Array(len),
					code;
				for (var i = 0; i < len; i++) {
					code = hex.charCodeAt(i);
					if (48 <= code && code < 58) {
						code -= 48;
					} else {
						code = (code & 0xdf) - 65 + 10;
					}
					a[i] = code;
				}
		
				return a.reduce(function(acc, c) {
					acc = 16 * acc + c;
					return acc;
				}, 0);
			},
			array16_to_number(arrayValue) {
				const newArray = arrayValue.filter(item => String(item) !== '00' || String(item) !== '0')
				const _number16 = newArray.map(hex => parseInt(hex, 16).toString(16)).join('')
				return parseInt(`0x${_number16}`)
			},

			string2buffer(str) {
				let val = ""
				if (!str) return;
				let length = str.length;
				let index = 0;
				let array = []
				while (index < length) {
					array.push(str.substring(index, index + 2));
					index = index + 2;
				}
				val = array.join(",");
				// 将16进制转化为ArrayBuffer
				return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				})).buffer
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			
			addColonEveryTwoChars(str,symbol) {
			  let result = '';
			  for (let i = 0; i < str.length; i += 2) {
			    result += str.substr(i, 2) + symbol;
			  }
			  // 如果最后一位是单个字符，则直接添加
			  if (str.length % 2 === 1) {
			    result += str.charAt(str.length - 1);
			  }
			  // 移除最后一个冒号
			  result = result.substr(0, result.length - 1);
			  return result;
			},
			snacode() {
				let that = this;
				let myblue = []
				uni.scanCode({
					success: function(res) {
						console.log(res)
						let str = that.addColonEveryTwoChars(res.result.split(' ')[0],':')
						let name = res.result.split(' ')[1]+res.result.split(' ')[2]
						let obj = {
							name:name,
							deviceId:str.toUpperCase()
						}
						that.createBLEConnection(obj,'0x01')
						
					},
					fail: (err => {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						})
					})
				 
				});
			},
		},
		onBackPress(options) {
			return true
			// if(uni.$_getSystem() == 'android'){
			// 	return this.valueChange()
			// }
			
			// if(options.from === 'backbutton'){
			// 		return true
			// 	}
			// 	// 否则则允许返回
			// 	return false;
		},
	}
</script>

<style lang="scss" scoped>
	/deep/.u-back-wrap{
		background: url(@/static/img/common/topBack.png) no-repeat center / 40rpx 40rpx;
	}
	/deep/.u-icon-wrap{
		opacity: 0;
		padding-left: 30rpx;
	}
	page{
		background: #f5f5f5 !important;
	}
	.content{
		padding: 40rpx 30rpx 200rpx;
	}
	.back{
		margin-bottom: 50rpx;
		image{
			width: 40rpx;
			height: 40rpx;
		}
	}
	.yjTitle{
		font-size: 60rpx;
		font-weight: bold;
		color: #000;
		margin-bottom: 60rpx;
	}
	.subTitle{
		color: #999;
		font-size: 28rpx;
		margin-bottom: 20rpx;
	}
	.box{
		width: 100%;
		background: #ffffff;
		border-radius: 24rpx;
		box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0,0,0,0.10); 
		margin-bottom: 40rpx;
		// padding: 0 30rpx;
		min-height: 150rpx;
		box-sizing: border-box;
		overflow: hidden;
	}
	.box1{
		height: 150rpx;
		color: #aaa;
		font-size: 30rpx;
		padding-left: 50rpx;
	}
	.my-box{
		.item2{
			height: 150rpx;
			padding: 0 30rpx;
		}
		.img1{
			width: 38rpx;
			height: 52rpx;
		}
		.img2{
			width: 37rpx;
			height: 27rpx;
		}
		.title{
			font-size: 30rpx;
			color: #000;
			font-family: $uni-font-family-Bold;
			margin-bottom: 10rpx;
		}
		.info{
			font-size: 24rpx;
			color: #666;
			font-family: $uni-font-family-Medium;
		}
	}
	.other-box{
		min-height: 350rpx;
	}
	.item{
		height: 100rpx;
		line-height: 100rpx;
		border-bottom: 1rpx solid #eee;
		font-size: 32rpx;
		color: #111;
		padding: 0 30rpx;
	}
	.hover{
		background-color: #efefef;
	}
	.sys{
		width: 100%;
		position: fixed;
		bottom: 100rpx;
		left: 0;
		z-index: 2;
		padding: 0 60rpx;
		box-sizing: border-box;
		.btn{
			height: 96rpx;
			line-height: 96rpx;
			background: #e0e0e0;
			border-radius: 45rpx;
			text-align: center;
			font-size: 30rpx;
			color: #000;
			font-family: $uni-font-family-Heavy;
		}
	}
</style>
